package com.wangshouyu.mp.base.request;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

/**
 * @author 王守钰
 * @date 2020年12月04日 19:31
 * @description ByteArrayBody
 */
public class ByteArrayBody implements ResponseBody {

    private final byte[] data;

    public ByteArrayBody(byte[] data) {
        this.data = data;
    }

    public static ResponseBody orNull(byte[] data) {
        if (data == null) {
            return null;
        }
        return new ByteArrayBody(data);
    }

    public static ResponseBody orNull(String text, Charset charset) {
        if (text == null) {
            return null;
        }
        if(null == charset){
            throw new RuntimeException("charset should not be null");
        }
        return new ByteArrayBody(text.getBytes(charset));
    }

    @Override
    public Integer length() {
        return data.length;
    }

    @Override
    public boolean repeatable() {
        return true;
    }

    @Override
    public InputStream inputStream() throws IOException {
        return new ByteArrayInputStream(data);
    }

    @Override
    public Reader reader(Charset charset) throws IOException {
        if(null == charset){
            throw new RuntimeException("charset should not be null");
        }
        return new InputStreamReader(inputStream(), charset);
    }

    @Override
    public void close() throws IOException {}

    @Override
    public String toString() {
        if (data == null) {
            return "Binary data";
        }
        try {
            return UTF_8.newDecoder().decode(ByteBuffer.wrap(data)).toString();
        } catch (CharacterCodingException ex) {
            return "Binary data";
        }
    }
}
